package com.mht2017.common.utils;

import java.io.UnsupportedEncodingException;

import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.apache.log4j.Logger;

public class ZKStringSerialize implements ZkSerializer {

	private static final Logger LOGGER = Logger.getLogger(ZKStringSerialize.class);
	private static final String actionName = "ZooKeeper序列化";

	@Override
	public byte[] serialize(Object data) throws ZkMarshallingError {
		if (data instanceof String) {
			try {
				return ((String) data).getBytes("UTF-8");
			} catch (UnsupportedEncodingException e) {
				LOGGER.error(String.format("%s-创建topic转换字符编码出错 -值: '%s' -出错: '%s'", actionName, data, e.getMessage()), e);
			}
		}
		return null;
	}

	@Override
	public Object deserialize(byte[] bytes) throws ZkMarshallingError {
		if (bytes == null) {
			return null;
		} else {
			try {
				return new String(bytes, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				LOGGER.error(String.format("%s-创建topic转换字符编码出错 -值: '%s' -出错: '%s'", actionName, bytes.toString(), e.getMessage()), e);
			}
		}
		return null;
	}
}
